package api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import donain.User;
import service.UserService;
import utilts.GetRequestJsonUtils;
import utilts.Response;
import utilts.ResponseCode;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

public class RegusterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getLocalAddr());
        System.out.println(req.getLocalName());
        System.out.println(req.getLocalPort());
        System.out.println(req.getServletPath());
        System.out.println(req.getServerName());
        System.out.println(req.getServerPort());
        System.out.println(req.getServletContext());
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        req.getRequestURL();
        JSONObject jsObject=null;
        Response build=null;
        try {
            jsObject= GetRequestJsonUtils.getRequestJsonObject(req);
        }catch (Exception e){
            e.printStackTrace();
             build=Response.build(ResponseCode.ERROR,e.getMessage());

        }
        String userString=jsObject.getString("user");
        User user= JSON.parseObject(userString,User.class);
        UserService userService= new UserService();
        user.setRegistTime(new Date(System.currentTimeMillis()));
       user.setActiveCode(UUID.randomUUID().toString());
//       if(user.getState()==1)
//       user.setRole("超级用户");
        if(userService.register(user)){
//            build=Response.build(ResponseCode.SUCCESS,"你已注册成功，快去登陆邮箱激活账号！");
            build=Response.build(ResponseCode.SUCCESS_REGISTERT,"快去登陆邮箱激活账号！");
                    }
        else {
            build=Response.build(ResponseCode.ERROR_REGISTERT);
        }
        resp.getWriter().write(JSON.toJSON(build).toString());
        resp.setContentType("application/json;charset=utf-8");
    }
}
